import { Tree } from "antd"
import { PageTitle } from "../../compnents/Title"
import style from "./index.module.css"
import { useEffect, useState } from "react"
import { useDispatch, useSelector } from "react-redux"
import { ROOT_STATE } from "../../store"
import { reqAllType } from "../../api/tagType"
import { changeTypeList } from "../../store/typeSlice"
import { reqGetAllInterView, reqGetInterviewById } from "../../api/interview"
import { InterViewData } from "../../Types/Api/interView"
interface DataNode {
  title: string
  key: string
  children?: DataNode[]
}
export const QA = () => {
  const dispatch = useDispatch()
  const typeList = useSelector(
    (state: ROOT_STATE) => state.typeReducer.typeList
  )
  const getTypeList = async () => {
    const { data: type } = await reqAllType()
    dispatch(changeTypeList(type))
  }

  const getInterView = async () => {
    const { data: iv } = await reqGetAllInterView()
    // iv ；[[Interview]]
    // typeList + iv => DataNode[]
    const arr = iv.map((item, index) => {
      // item = [iv, iv, iv, {_id, interViewTitle}]
      return {
        title: typeList[index].typeName,
        key: typeList[index]._id,
        children: item.map((v) => {
          return {
            title: v.interviewTitle,
            key: v._id,
          } as DataNode
        }),
      } as DataNode
    })
    setTreeData(arr)
  }
  const [iv, setIv] = useState<InterViewData>()
  const selectHandler = async (key: string) => {
    const { data } = await reqGetInterviewById(key)
    setIv(data)
  }

  const [treeData, setTreeData] = useState<DataNode[]>([])

  useEffect(() => {
    if (typeList.length === 0) {
      // dispatch(异步action)
      getTypeList()
    } else {
      // 有typelist
      getInterView()
    }
  }, [typeList])
  return (
    <div className={style.wrapper}>
      {/* 头部组件 */}
      <PageTitle title="面试题大全"></PageTitle>
      {/* 内容区 */}
      <div className={style.content}>
        {/* 左边目录（Tree) */}
        <div className={style.leftContent}>
          <Tree
            treeData={treeData}
            onSelect={(key, e) => !e.node.children && selectHandler(e.node.key)}
          ></Tree>
        </div>
        {/* 右边展示具体内容 */}
        <div className={style.rightContent}>
          {iv ? (
            <>
              <h1>{iv.interviewTitle}</h1>
              <div
                style={{ width: "100%" }}
                dangerouslySetInnerHTML={{ __html: iv.interviewContent }}
              ></div>
            </>
          ) : (
            <h2>请选择左侧面试题</h2>
          )}
        </div>
      </div>
    </div>
  )
}
